/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cinema.client.cinemaclient.managers;

import com.cinema.client.cinemaclient.constants.Constants;
import com.cinema.client.cinemaclient.model.Movie;
import java.util.ArrayList;

import java.util.List;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

/**
 *
 * @author Zsolt Szecsi
 */
public class MovieManager {

    public List<Movie> getAllMovies() {
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(Constants.BASE_URL + "Movies");
        return target.request(MediaType.APPLICATION_JSON_TYPE).get(new GenericType<List<Movie>>() {
        });
    }

    public Movie getMovieById(int id) {
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(Constants.BASE_URL + "Movies/" + id);
        Movie movieResponse = null;
        Response response = target.request(MediaType.APPLICATION_JSON_TYPE).get();
        if (response != null && Status.Family.SUCCESSFUL == response.getStatusInfo().getFamily()) {
            movieResponse = response.readEntity(Movie.class);
            return movieResponse;
        } else {
            System.err.println("There was an error fetching service response");
            System.err.println(response);
            return null;
        }
    }

    public Movie insertMovie(Movie movie) {
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(Constants.BASE_URL + "Movies");

        return target.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.entity(movie, MediaType.APPLICATION_JSON), Movie.class);
    }

    public Movie updateMovie(Movie movie) {
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(Constants.BASE_URL + "Movies");

        return target.request(MediaType.APPLICATION_JSON_TYPE).put(Entity.entity(movie, MediaType.APPLICATION_JSON), Movie.class);
    }

    public void deleteMovie(int id) {
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(Constants.BASE_URL + "Movies/" + id);

        target.request(MediaType.APPLICATION_JSON_TYPE).delete();
    }
}
